<script setup lang="ts">
import { reactive, ref, toRef } from 'vue'
import type { FormInst, FormRules } from 'naive-ui'
import { Rules } from '@/utils'
import { JBoltApi } from '@/utils/request'

const props = defineProps<{
    userId?: string
}>()

const resetPwdForm = reactive({
    newPwd: '',
    confirmPwd: ''
})
const isSubing = ref(false)
const form = ref<HTMLElement & FormInst>()

//校验规则定义
const rules: FormRules = {
    newPwd: new Rules().required('请输入新密码').minLength(3).value,
    confirmPwd: new Rules()
        .required('请输入密码再次确认')
        .eq(toRef(resetPwdForm, 'newPwd'), '两次输入的密码不一致').value
}

//表单提交时做校验
async function submit() {
    await form.value?.validate()
    if (isSubing.value) return
    isSubing.value = true

    try {
        let url = '/api/admin/user/resetPwd'
        let data = {
                userId: props.userId,
                newPwd: resetPwdForm.newPwd,
                reNewPwd: resetPwdForm.confirmPwd
            }
        let { error } = await JBoltApi.post(url, data)
        if (error) return
    } finally {
        isSubing.value = false
    }
}

defineExpose({
    submit
})
</script>

<template>
    <n-form
        ref="form"
        :rules="rules"
        label-placement="left"
        :label-width="140"
        :model="resetPwdForm"
    >
        <n-grid :cols="12" :x-gap="24">
            <n-form-item-grid-item :span="12" label="新密码" path="newPwd">
                <n-input
                    v-model:value="resetPwdForm.newPwd"
                    show-password-on="click"
                    type="password"
                />
            </n-form-item-grid-item>
            <n-form-item-grid-item :span="12" label="确认新密码" path="confirmPwd">
                <n-input
                    v-model:value="resetPwdForm.confirmPwd"
                    show-password-on="click"
                    type="password"
                    clearable
                />
            </n-form-item-grid-item>
        </n-grid>
    </n-form>
</template>

<style scoped></style>
